#include "brightness_sensor_mode.h"
#include "systime.h"
#include "adc_driver.h"

#define LIGHT_POS_UPDATE_TIME 20 // 单位ms,检测光感设置更新时间

// 光感设置阈值
#define BRIGHTNESS_THRESHOLD_DEFAULT 450         // 默认亮度 实测511
#define BRIGHTNESS_THRESHOLD_CUSTOM 600          // 客户定制亮度 实测661
#define BRIGHTNESS_THRESHOLD_SENSOR_DISABLED 700 // 光感无效 实测783
#define BRIGHTNESS_THRESHOLD_VAC_MODE 800        // VAC模式 实测810

typedef enum
{
    STATE_INITIALIZING,
    STATE_UPDATE,
} brightness_sensor_mode_check_state_e;

static struct
{
    timestamp_t time;
    brightness_sensor_mode_check_state_e state;
    brightness_sensor_mode_e mode; // 光感设置
} brightness_mode_ctx;

static brightness_sensor_mode_e get_brightness_sensor_mode_value(void);

void brightness_sensor_mode_init(void)
{
    brightness_mode_ctx.state = STATE_INITIALIZING;
    brightness_mode_ctx.mode = BRIGHTNESS_DEFAULT;
}

brightness_sensor_mode_e get_brightness_sensor_mode(void)
{
    return brightness_mode_ctx.mode;
}

void brightness_sensor_mode_check_task(void)
{
    switch (brightness_mode_ctx.state)
    {
    case STATE_INITIALIZING:
        brightness_mode_ctx.mode = get_brightness_sensor_mode_value();
        relative_time_add_ms(&brightness_mode_ctx.time, LIGHT_POS_UPDATE_TIME);
        brightness_mode_ctx.state = STATE_UPDATE;
        printf("the LIGHT mode:%d \r\n", brightness_mode_ctx.mode);
        break;
    case STATE_UPDATE:
        if (is_relative_time_timeout(&brightness_mode_ctx.time))
        {
            brightness_mode_ctx.mode = get_brightness_sensor_mode_value();
            relative_time_add_ms(&brightness_mode_ctx.time, LIGHT_POS_UPDATE_TIME);
        }
        break;

    default:
        break;
    }
}

static brightness_sensor_mode_e get_brightness_sensor_mode_value(void)
{
    uint16_t val = get_brightness_val();

    if (val <= BRIGHTNESS_THRESHOLD_CUSTOM)
        return BRIGHTNESS_DEFAULT;
    else if (val <= BRIGHTNESS_THRESHOLD_SENSOR_DISABLED)
        return BRIGHTNESS_CUSTOM;
    else if (val <= BRIGHTNESS_THRESHOLD_VAC_MODE)
        return BRIGHTNESS_SENSOR_DISABLED;
    else
        return BRIGHTNESS_VAC_MODE;
}
